/*
 * Copyright 2007 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0

 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the

 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.gwt.util.compat;

import com.sun.source.tree.Tree;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import javax.lang.model.element.Modifier;

public class MethodNode implements Comparable<MethodNode> {
  String name;
  String rettype;
  Set<Modifier> mods;
  List<String> exceptions = new ArrayList<String>();
  List<FieldNode> params;
  
  public MethodNode(String n, Tree r, Set<Modifier> m, List<FieldNode> p) {
    name = n;
    if (r != null)
      rettype = r.toString();
    else rettype = "";
    mods = m;
    if (p == null)
      params = new ArrayList<FieldNode>();
    else
      params = p;
  }
  
  public void addException(String exc) {
    exceptions.add(exc);
  }
  
  public String toString() {
    String ret = "";
    for (Modifier m : mods)
      ret += m.toString() + " ";
    ret += rettype + " " + name + "(";
    for (FieldNode f : params)
      ret += f.toString() + ", ";
    if (!params.isEmpty())
      ret = ret.substring(0, ret.length() - 2);
    ret += ")";
    return ret;
  }

  public int compareTo(MethodNode o) {
    int testName = name.compareTo(o.name);
    if (testName != 0)
      return testName;
    ListIterator<FieldNode> l1 = params.listIterator();
    ListIterator<FieldNode> l2 = o.params.listIterator();
    while (true) {
      if (!l1.hasNext()) {
        if (!l2.hasNext())
          return 0;
        return -1;
      }
      if (!l2.hasNext())
        return 1;
      String t1 = l1.next().type;
      String t2 = l2.next().type;
      int comp = t1.compareTo(t2);
      if (comp != 0)
        return comp;
    }
  }

  public boolean equals(Object obj) {
    return compareTo((MethodNode) obj) == 0;
  }
  
}
